package cn.fz.ssedemo.interceptor;

import cn.fz.ssedemo.domain.vo.ResultVO;
import cn.fz.ssedemo.utils.ContextUtils;
import cn.fz.ssedemo.utils.JwtUtils;
import cn.fz.ssedemo.utils.ServletUtils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.jwt.JWTPayload;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginValidateInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求url
        String url = request.getRequestURL().toString();
        log.info("url: {}",url);
        // 2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if (url.contains("login") || url.contains("media")) {
            log.info("登录放行...");
            return true;
        }
        if (request.getRequestURI().contains("swagger")
                || request.getRequestURI().contains("api-docs")
                || request.getRequestURI().equals("/doc.html")
                || request.getRequestURI().equals("/favicon.ico")
                || request.getRequestURI().endsWith(".js")
                || request.getRequestURI().endsWith(".css")
        ) {
            log.info("knife4j放行...");
            return true;
        }
        // 3.获取请求头中的令牌（token）
        String realToken = null;
        String userAgent = request.getHeader("User-Agent");
        if(UserAgentUtil.parse(userAgent).isMobile()){
            realToken = request.getHeader("token");
        }else{
            realToken = request.getHeader("Authorization");
        }
        if(StrUtil.isEmpty(realToken)){
            // 什么都没有就是没登录
            ResultVO<String> error = ResultVO.failed("NOT_LOGIN","401");
            ServletUtils.responseWriter(response,error);
            return false;
        }
        // 每次保存前先清理
        ContextUtils.removeCurrentId();
        // 4.判断令牌如果是不存在以及过期,返回错误结果（未登录）
        JWTPayload jwtPayload = null;
        try {
            jwtPayload = JwtUtils.parseToken(realToken);
        } catch (Exception e) {
            log.info("解析令牌失败: {}",e.getMessage());
            ResultVO<String> error = ResultVO.failed("TOKEN_EXPIRATION","4001");
            ServletUtils.responseWriter(response,error);
            return false;
        }
        // 保存到ThreadLocal后续其他层都可以获取到，只要是在这次请求的线程中都可以共享获取到
        ContextUtils.setCurrentId(Integer.parseInt(jwtPayload.getClaim("id").toString()));
        return true;
    }
}
